import 'dart:convert';
import 'dart:developer';
import 'dart:io';
import 'package:flutter/foundation.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter/services.dart';
import 'package:flutter_with_bmap/consts/msg_type.dart';
import 'package:flutter_with_bmap/entity/alarm.dart';
import 'package:flutter_with_bmap/entity/green_wave.dart';
import 'package:flutter_with_bmap/entity/light_hv.dart';
import 'package:flutter_with_bmap/entity/vehicle.dart';
import 'package:flutter_with_bmap/models/vehicle_hv_info.dart';
import 'package:flutter_with_bmap/pages/home/widgets/lightSection.dart';
import 'package:flutter_with_bmap/pages/home/widgets/pannel.dart';
import 'package:flutter_with_bmap/pages/home/widgets/setting.dart';
import 'package:flutter_with_bmap/util/method_channel_util.dart';
import 'package:flutter_with_bmap/util/socket/socket.dart';
import 'package:flutter_with_bmap/util/toast.dart';
import 'package:provider/provider.dart';

class HomePage extends StatefulWidget {
  const HomePage({super.key});

  @override
  State<HomePage> createState() => HomePageState();
}

class HomePageState extends State<HomePage> {
  late WebSocket socket;
  var vehicleHvInfo = VehicleHvInfo();
  MethodChannel methodChannel = MethodChannelUtil.methodChannel;
  initMethodChannel() {
    methodChannel.setMethodCallHandler((call) {
      if (call.method == "alarm") {
        String data = call.arguments;
        var list = jsonDecode(data);
        for (var item in list) {
          handleJavaSocketMsg(item);
        }
      } else if (call.method == "vehicle_hv") {
        vehicleHvInfo
            .setVehicleInfo(Vehicle.fromJson(jsonDecode(call.arguments)));
      } else if (call.method == "light_hv") {
        vehicleHvInfo
            .setLightInfo(LightHv.fromJson(jsonDecode(call.arguments)));
      } else if (call.method == "green_wave") {
        vehicleHvInfo
            .setGreenWave(GreenWave.fromJson(jsonDecode(call.arguments)));
      }
      return Future.value("消息flutter已收到");
    });
  }

  @override
  void initState() {
    super.initState();
    initMethodChannel();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        body: MultiProvider(
            providers: [
              ChangeNotifierProvider(create: (context) => vehicleHvInfo)
            ],
            child: Stack(alignment: Alignment.topCenter, children: [
              PlatformViewLink(
                  surfaceFactory: ((context, controller) {
                    return AndroidViewSurface(
                        controller: controller as AndroidViewController,
                        hitTestBehavior: PlatformViewHitTestBehavior.opaque,
                        gestureRecognizers: const <
                            Factory<OneSequenceGestureRecognizer>>{});
                  }),
                  onCreatePlatformView: (params) {
                    AndroidViewController controller =
                        PlatformViewsService.initExpensiveAndroidView(
                            id: params.id,
                            viewType: "BMapView",
                            layoutDirection: TextDirection.ltr,
                            creationParams: const <String, dynamic>{
                              "center": [
                                29.568996245338923,
                                106.55843415537664
                              ],
                              "zoom": 21
                            },
                            creationParamsCodec: const StandardMessageCodec(),
                            onFocus: () => params.onFocusChanged(true));
                    controller.addOnPlatformViewCreatedListener(
                        params.onPlatformViewCreated);
                    controller.addOnPlatformViewCreatedListener((id) {
                      // getOrgsData();
                    });
                    return controller;
                  },
                  viewType: "BMapView"),
              const Positioned(
                  left: 0,
                  top: 0,
                  child: Padding(
                    padding: EdgeInsets.fromLTRB(20, 60, 0, 0),
                    child: Pannel(),
                  )),
              const Positioned(top: 10, child: LightSection())
            ])),
        drawer: const Drawer(
            width: 400,
            backgroundColor: Color.fromRGBO(249, 249, 249, 1),
            child: Setting()),
        drawerEnableOpenDragGesture: false);
  }

  initSocket() async {
    socket = await WebSocket.connect('ws://bamboo-os.org:6310');
    socket.listen((event) {
      var res = json.decode(event);
      if (res["type"] == 0) {
        //交通参与者
      }
    }, onError: (error) {
      log('报错了');
      log(error);
    }, onDone: () {
      log('连接关闭时响应');
    }, cancelOnError: true);
  }

  initObuSocket() async {
    ClientSocket socket = ClientSocket("bamboo-os.org", 6310);
    // socket.subscribe(this);
  }

  handleJavaSocketMsg(Map data) {
    log("这里是预警消息");
    int tag = data["tag"];
    var jsonData = data["data"];
    if (tag == 10003) {
      //	碰撞预警。
      Alarm alarm = Alarm.fromJson(jsonData);
      OverLayUtil.showNotify("碰撞预警", alarm.toast ?? "",
          duration: Duration(seconds: alarm.time_display ?? 2),
          msgType: MsgType.fromCode('10003'));
    } else if (tag == 10004) {
      //RSI事件类预警信息
      Alarm alarm = Alarm.fromJson(jsonData);
      String title = "";
      switch (alarm.alarm_type) {
        case 100:
          title = "道路危险状况预警";
          break;
        case 101:
          title = "限速预警";
          break;
        case 102:
          title = "车内标牌预警";
          break;
        case 103:
          title = "前方拥堵预警";
          break;
      }
      OverLayUtil.showNotify(title, alarm.toast ?? "",
          duration: Duration(seconds: alarm.time_display ?? 2),
          msgType: MsgType.fromCode('10004${alarm.alarm_type}'));
    } else if (tag == 10005) {
      //V2V类预警信息
      Alarm alarm = Alarm.fromJson(jsonData);
      String title = "";
      switch (alarm.alarm_type) {
        case 100:
          title = "紧急制动预警";
          break;
        case 101:
          title = "异常车辆预警";
          break;
        case 102:
          title = "车辆失控预警";
          break;
        case 103:
          title = "紧急车辆预警";
          break;
      }
      OverLayUtil.showNotify(title, alarm.toast ?? "",
          duration: Duration(seconds: alarm.time_display ?? 2),
          msgType: MsgType.fromCode('10005${alarm.alarm_type}'));
    } else if (tag == 10006) {
      //场景类预警消息
      Alarm alarm = Alarm.fromJson(jsonData);
      String title = "";
      switch (alarm.alarm_type) {
        case 100:
          title = "交叉路口碰撞预警";
          break;
        case 101:
          title = "左转辅助预警";
          break;
        case 102:
          title = "盲区辅助预警";
          break;
        case 103:
          title = "逆向超车预警";
          break;
        case 104:
          title = "弱势交通参与者碰撞预警";
          break;
      }
      OverLayUtil.showNotify(title, alarm.toast ?? "",
          duration: Duration(seconds: alarm.time_display ?? 2),
          msgType: MsgType.fromCode('10006${alarm.alarm_type}'));
    } else if (tag == 10007) {
      //交通灯类预警消息

    }
  }
}
